import { Algorithm } from "../types"

// Schema 定义
interface DHCDSNode {
  id: any
  type: string
  attributes: Record<string, any>
}

interface DHCDSEdge {
  source: any
  target: any
  type?: string
  weight?: number
  attributes: Record<string, any>
}

interface DHCDSGraph {
  nodes: DHCDSNode[]
  edges: DHCDSEdge[]
}

interface Community {
  id: string
  nodes: any[]
  stability: number
  description: string
}

interface DHCDSTimeStepResult {
  time: number
  communities: Community[]
  node_communities: Record<string, string[]>
}

interface DHCDSInputParams {
  graph_sequence: DHCDSGraph[]
  stability_weight: number
  embedding_dim: number
  num_clusters: number
  node_type_weights?: Record<string, number>
}

interface DHCDSOutputParams {
  results: DHCDSTimeStepResult[]
  algorithm: string
  parameters: Record<string, any>
  community_evolution: Record<string, any>[]
}

interface AlgorithmRequest {
  task_id: string
  task_callback_url?: string
  input_params: {
    dhcds_params: DHCDSInputParams
  }
}

// 算法实现
export const dynamicHeterogeneousAnomalyDetection: Algorithm = {
  name: "动态异构图社区检测(DHCDS)算法",
  description: "基于动态异构图社区检测(DHCDS)算法，用于识别图结构中随时间变化的社区结构",
  configOptions: [
    {
      id: "stability_weight",
      label: "稳定性权重",
      type: "number",
      defaultValue: 0.6,
      placeholder: "0.6"
    },
    {
      id: "embedding_dim",
      label: "嵌入维度",
      type: "number",
      defaultValue: 128,
      placeholder: "128"
    },
    {
      id: "num_clusters",
      label: "社区数量",
      type: "number",
      defaultValue: 10,
      placeholder: "10"
    },
    {
      id: "node_type_weights",
      label: "节点类型权重",
      type: "textarea",
      placeholder: "{'用户': 1.0, '文章': 0.8, '评论': 0.5}"
    },
    {
      id: "inputData",
      label: "输入数据",
      type: "textarea",
      placeholder: `请输入JSON格式的图序列数据，例如：
{
  "graph_sequence": [
    {
      "nodes": [
        {
          "id": "u1",
          "type": "用户",
          "attributes": {"age": 25, "gender": "男"}
        }
      ],
      "edges": [
        {
          "source": "u1",
          "target": "a1",
          "type": "发布",
          "weight": 1.0,
          "attributes": {"timestamp": "2023-01-01"}
        }
      ]
    }
  ]
}`
    }
  ],
  execute: async (config) => {
    try {
      // 生成唯一的任务ID
      const taskId = `dhcds_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
      
      // 解析输入数据
      let graphData: { graph_sequence: DHCDSGraph[] }
      try {
        graphData = JSON.parse(config.inputData)
      } catch (e) {
        throw new Error("输入数据必须是有效的JSON格式")
      }

      // 验证输入数据结构
      if (!graphData.graph_sequence || !Array.isArray(graphData.graph_sequence)) {
        throw new Error("输入数据必须包含graph_sequence数组")
      }

      // 解析节点类型权重
      let nodeTypeWeights: Record<string, number> | undefined
      if (config.node_type_weights) {
        try {
          nodeTypeWeights = JSON.parse(config.node_type_weights)
        } catch (e) {
          throw new Error("节点类型权重必须是有效的JSON格式")
        }
      }

      // 准备请求数据
      const requestData: AlgorithmRequest = {
        task_id: taskId,
        task_callback_url: "",
        input_params: {
          dhcds_params: {
            graph_sequence: graphData.graph_sequence,
            stability_weight: Number(config.stability_weight) || 0.6,
            embedding_dim: Number(config.embedding_dim) || 128,
            num_clusters: Number(config.num_clusters) || 10,
            node_type_weights: nodeTypeWeights
          }
        }
      }

      // 创建任务
      const createResponse = await fetch("http://172.16.4.151:1122/api/dhcds/create", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(requestData)
      })

      if (!createResponse.ok) {
        const errorData = await createResponse.json()
        if (createResponse.status === 422) {
          const validationErrors = errorData.detail || []
          const errorMessages = validationErrors.map((err: any) => 
            `${err.loc?.join('.')}: ${err.msg}`
          ).join('\n')
          throw new Error(`数据验证错误:\n${errorMessages}`)
        }
        throw new Error(errorData.detail || "创建任务失败")
      }

      // 执行任务
      const executeResponse = await fetch(`http://172.16.4.151:1122/api/dhcds/execute/${taskId}`, {
        method: "POST"
      })

      if (!executeResponse.ok) {
        const errorData = await executeResponse.json()
        throw new Error(errorData.detail || "执行任务失败")
      }

      // 轮询获取结果
      let result
      let attempts = 0
      const maxAttempts = 60

      while (attempts < maxAttempts) {
        const getResultResponse = await fetch(`http://172.16.4.151:1122/api/dhcds/result/${taskId}`)
        
        if (!getResultResponse.ok) {
          const errorData = await getResultResponse.json()
          throw new Error(errorData.detail || "获取结果失败")
        }

        result = await getResultResponse.json()

        if (result.task_status === "COMPLETED") {
          break
        } else if (result.task_status === "FAILED") {
          throw new Error(result.error_message || "任务执行失败")
        }

        await new Promise(resolve => setTimeout(resolve, 1000))
        attempts++
      }

      if (attempts >= maxAttempts) {
        throw new Error("任务执行超时")
      }

      // 处理结果
      const outputParams: DHCDSOutputParams = result.output_params.dhcds_results
      
      // 检查communities结构并进行适当处理
      const resultText = `社区检测完成：
时间序列长度: ${outputParams.results.length}
检测到的社区总数: ${outputParams.results.reduce((sum, timeStep) => {
  // 检查communities是否为数组
  if (Array.isArray(timeStep.communities)) {
    return sum + timeStep.communities.length;
  } else if (typeof timeStep.communities === 'object') {
    // 如果是字典/对象，计算键的数量
    return sum + Object.keys(timeStep.communities).length;
  }
  return sum;
}, 0)}`

      // 根据结果展示相关重要的结果
      const importantResults = outputParams.results.map(timeStep => {
        // 计算社区数
        const communityCount = Array.isArray(timeStep.communities) 
          ? timeStep.communities.length 
          : Object.keys(timeStep.communities).length;
        
        // 计算平均稳定性，根据communities的实际结构调整
        let stabilityAverage = 0;
        if (Array.isArray(timeStep.communities) && timeStep.communities.length > 0) {
          stabilityAverage = timeStep.communities.reduce((sum, community) => 
            sum + (community.stability || 0), 0) / timeStep.communities.length;
        } else if (typeof timeStep.communities === 'object') {
          // 如果communities是对象/字典，我们可能需要根据实际数据结构调整
          // 这里假设没有稳定性信息，或者在其他地方
          stabilityAverage = 0;
        }
        
        return {
          time: timeStep.time,
          communityCount,
          stabilityAverage
        };
      }).sort((a, b) => b.stabilityAverage - a.stabilityAverage).slice(0, 5);

      const importantResultsText = `重要结果概览:
${importantResults.map(result => 
  `- 时间步 ${result.time}: 检测到的社区总数: ${result.communityCount}, 平均稳定性: ${result.stabilityAverage.toFixed(4)}`
).join('\n')}`

      return {
        result: `${resultText}\n${importantResultsText}`,
        steps: result.metrics || [],
        executionTime: result.execution_time,
        details: {
          results: outputParams.results,
          parameters: outputParams.parameters,
          communityEvolution: outputParams.community_evolution,
          metrics: result.metrics,
          importantResults: importantResults
        }
      }
    } catch (e) {
      throw e
    }
  }
} 